// Copyright (c) 2008 Davy Brion (ralinx@davybrion.com)
// All rights reserved.
// 
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
// 
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright notice,
//       this list of conditions and the following disclaimer in the documentation
//       and/or other materials provided with the distribution.
//     * Neither the name of Davy Brion nor the names of the
//       contributors may be used to endorse or promote products derived from this
//       software without specific prior written permission.
// 
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

using System;
using System.Collections.Generic;
using System.Linq;
using Albatross.Common;
using Albatross.Common.Messaging;
using Albatross.Common.Exceptions;

namespace Albatross.ServerSide.Messaging
{
	public class RequestProcessor : IRequestProcessor
	{
		// the server-side implementation should be stateless, but the IRequestProcessor
		// interface defines the Dispose method, so we just provide an empty one here
		public void Dispose()
		{
		}

		public virtual Response[] Process( params Request[] requests )
		{
			OnProcessing( requests );
			List<Response> results = ProcessCore( requests );
			OnProcessed( requests, results );

			return results.ToArray();
		}

		protected virtual void OnProcessed(Request[] requests, List<Response> results)
         {
         }

		protected virtual List<Response> ProcessCore( Request[] requests  )
		{
			if ( requests == null )
			{
				return null;
			}

			var responses = new List<Response>( requests.Length );

			try
			{
				foreach ( var request in requests )
				{
					responses.Add( ResolveHandler( request ) );
				}
			}
			catch ( System.Exception ex )
			{
				responses.Add( OnException( ex ));
			}
			return responses;
		}        
		
		protected virtual void OnProcessing(Request[] requests)
         {
         }
        
		protected virtual Response ResolveHandler( Request request )
		{
			using ( var handler = ( IRequestHandler )IoC.Container.Resolve(  request.GetType(  )  ) )  //
			{
				return ExecuteHandler( request, handler );
			}
		}

		protected virtual Response ExecuteHandler( Request request, IRequestHandler handler )
		{
			try
			{
				handler.OnHandling( request );
				var response = handler.Handle( request );
				handler.OnHandled(  );

				return response;
			}
			catch ( System.Exception ex )
			{
				var response = handler.OnException( ex );
				if( response == null )
						throw;

				return  response;
			}
		}

		protected virtual Response OnException(Exception ex)
         {
         	if( ex.GetType(  ) == typeof( AlbatrossException ) )
				return GenerateErrorResponseForClient( ((AlbatrossException)ex).Message, ((AlbatrossException)ex).Code );
			else if( ex.GetType(  ) == typeof( Castle.MicroKernel.ComponentNotFoundException ) )
				return GenerateErrorResponseForClient( ex.Message, ( Int32 )ErrorType.HandlerNotFound );
			else
				return GenerateErrorResponseForClient( ex.Message, ( Int32 )ErrorType.RequestProcessorUnHandledException );

         }
		
		protected virtual ErrorResponse GenerateErrorResponseForClient( String message, Int32 ErrorCode )
		{
			//Should log exception details.
			return new ErrorResponse()
			{
				StatusInfo = message,
				StatusType = ErrorCode
			};
		}

	}
}